<template>
  <div>
    <el-card>
      <CategorySelector :isShowList="isShowList" @changeCategory="changeCategory"></CategorySelector>
    </el-card>
    <el-card style="margin-top: 20px">
      <!--  列表页-->
      <div v-show="isShowList">
        <el-button type="primary" icon="el-icon-plus" :disabled="!category3Id" @click="addAttr">添加属性</el-button>
        <el-table
          :data="attrList"
          style="width: 100%" border>
          <el-table-column
            prop="prop"
            align="center"
            type="index"
            label="序号"
            width="80">
          </el-table-column>
          <el-table-column
            prop="attrName"
            label="属性名称"
            width="150">
          </el-table-column>
          <el-table-column
            prop="prop"
            label="属性值列表"
            width="width">
            <template slot-scope="{row,$index}">
              <!--           @close="handleClose(tag)" -->
              <el-tag
                :key="attrValue.id"
                v-for="(attrValue,index) in row.attrValueList"
              >
                {{ attrValue.valueName }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column
            prop="prop"
            label="操作"
            width="150">
            <template slot-scope="{row,$index}">
              <HintButton type="warning" size='mini' icon="el-icon-edit" title="修改"
                          @click="updateAttr(row)"></HintButton>
              <HintButton type="danger" size='mini' icon="el-icon-delete" title="删除"
                          @click="deleteRow(row)"></HintButton>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <!-- 添加和修改页面-->
      <div v-show="!isShowList">
        <!--        ref="form" :model="form"-->
        <el-form :inline="true" :model="attrForm">
          <el-form-item label="属性名">
            <el-input v-model="attrForm.attrName" placeholder="请输入属性名"></el-input>
          </el-form-item>
        </el-form>
        <el-button type="primary" icon="el-icon-plus" @click="addAttrValue" :disabled="!attrForm.attrName">添加属性值</el-button>
        <el-button @click="isShowList=true">取消</el-button>
        <el-table
          :data="attrForm.attrValueList"
          style="width: 100%;margin-top: 20px" border>
          <el-table-column
            prop="prop"
            align="center"
            type="index"
            label="序号"
            width="80">
          </el-table-column>
          <el-table-column
            prop="prop"
            label="属性值名称"
            width="width">
            <template slot-scope="{row,$index}">
              <el-input
                :ref="$index"
                v-if="row.isEdit"
                v-model="row.valueName"
                placeholder="请输入属性值名称"
                @keyup.enter.native="toButton(row)"
                @blur="toButton(row)"
              ></el-input>
              <el-button v-else @click="toInput(row,$index)">{{ row.valueName }}</el-button>
            </template>
          </el-table-column>
          <el-table-column
            prop="prop"
            label="操作"
            width="width">
            <template slot-scope="{row,$index}">
              <el-popconfirm
                :title="`你确定要删除${row.valueName}吗`"
                @onConfirm="attrForm.attrValueList.splice($index,1)"
              >
                <HintButton slot="reference" type="danger" size="mini" title="删除" icon="el-icon-delete"></HintButton>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
        <el-button type="primary" @click="save" :disabled="attrForm.attrValueList.length===0">保存</el-button>
        <el-button @click="isShowList=true">取消</el-button>
      </div>
    </el-card>
  </div>
</template>

<script>
import cloneDeep from "lodash/cloneDeep";

export default {
  name: "AttrList",
  data() {
    return {
      category1Id: '',
      category2Id: '',
      category3Id: '',
      attrList: [],
      inputVisible: false,
      inputValue: '',
      isShowList: true,
      attrForm: {
        attrName: "",
        attrValueList: [
          /*  {
            attrId: 3444
            id: 9578
            valueName: ""
            }*/
        ],
        categoryId: 0,
        categoryLevel: 3,
      }
    }
  },
  methods: {
    //获取子组件传过来的信息
    changeCategory({categoryId, level}) {
      if (level === 1) {
        //清空
        this.category2Id = ''
        this.category3Id = ''
        this.attrList = [],
          this.category1Id = categoryId
      } else if (level === 2) {
        //清空
        this.category3Id = ''
        this.attrList = [],
          this.category2Id = categoryId
      } else {
        //清空
        this.category3Id = ''
        this.attrList = [],
          this.category3Id = categoryId
        this.getAttrInfoList()
      }
    },
    async getAttrInfoList() {
      let {category1Id, category2Id, category3Id} = this
      try {
        const result = await this.$API.attr.getAttrInfoList(category1Id, category2Id, category3Id)
        if (result.code === 200 || result.code === 20000) {
          this.attrList = result.data
        }
      } catch (error) {
        this.$message.error('请求数据失败')
      }
    },
    //点击添加属性按钮
    addAttr() {
      this.isShowList = false
      this.attrForm = {
        categoryLevel: 3,
        attrName: "",
        attrValueList: [],
        categoryId: this.category3Id,
      };
    },
    //点击修改按钮
    updateAttr(row) {
      this.isShowList = false
      // this.attrForm = {...row}
      //由于属性对象当中属性值列表也是对象数据，浅拷贝属性值列表数据还是同一个，所以浅拷贝搞不定对象内部的对象数据
      this.attrForm = cloneDeep(row)
      this.attrForm.attrValueList.forEach(item => {
        // item.isEdit = false
        // item.isEdit = false isEdit不是响应式的属性，因为一上来data内部没这个属性
        //这个属性是点击按钮才添加的，此时，数据监视早都结束了，isEdit不可能被监视到，添加的太晚了
        // 它就不是响应式，修改的时候，也不会影响到页面
        this.$set(item, 'isEdit', false) //这样添加新的属性才是响应式的
      })
    },
    //添加属性值
    addAttrValue() {
      this.attrForm.attrValueList.push({
        attrId: this.attrForm.id,
        valueName: "",
        isEdit: true //由于是新添加的属性值，那么isEdit是true代表目前应该是编辑模式
      })
      //自动获取焦点
      this.$nextTick(() => {
        this.$refs[this.attrForm.attrValueList.length - 1].focus()
      })
    },
    //从button切换成input 编辑模式
    toInput(row, index) {
      /*this.inputVisible = true//切换成input*/
      row.isEdit = true
      //赋值完成 input还没创建完成
      this.$nextTick(() => {
        this.$refs[index].focus()// 让对应的点击这项input自动获取焦点
      })

    },
    //input失去焦点时或者回车事件 切换为button按钮 切换为查看模式
    toButton(row) {
      //1.判断数据是否为空
      if (row.valueName.trim() === '') {
        row.valueName = ''
        return
      }
      //2.看下是否重复
      let isRepeat = this.attrForm.attrValueList.some(item => {
        if (item !== row) {
          return item.valueName === row.valueName
        }
      })
      if (isRepeat) {
        this.$message.success('属性值不能重复')
        row.valueName = ''
        return
      }
      row.isEdit = false//切换成button
    },
    //点击保存按钮
    async save() {
      //收集数据
      /*    this.attrForm = {
            categoryLevel: 3,
            attrName: "",
            attrValueList: [],
            categoryId: this.category3Id,
          };*/
      let attr = this.attrForm
      //整理参数 1.属性名如果为空, 从属性值列表中去除
      attr.attrValueList = attr.attrValueList.filter(item => {
        if (item.valueName !== "") {
          delete item.isEdit
          return true
        }
      })
      //2.属性值列表如果没有属性值 不发请求
      if (attr.attrValueList.length === 0) {
        this.$message.info('属性的属性值列表必须有值')
        return
      }
      //发请求
      try {
        const result = await this.$API.attr.addUpdate(attr)
        if (result.code === 200 || result.code === 20000) {
          this.$message.success('属性保存成功')//提示
          this.isShowList = true//回到列表页
          await this.getAttrInfoList()//重新获取数据
        }
      } catch (error) {
        this.$message.error('属性保存请求失败')
      }
      //整理数据
      //发请求
      //成功
      //失败
    },
//点击列表页的删除按钮 获取id 发请求删除
    async deleteRow(row) {
      try {
        const result = await this.$API.attr.delete(row.id)
        if (result.code===200||result.code===20000){
          this.$message.success('删除成功')
         await this.getAttrInfoList()//重新获取列表
        }
      } catch (error) {
      this.$message.error('删除失败')
      }
    }
  },
}
</script>

<style>
.el-tag + .el-tag {
  margin-left: 10px;
}

.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}

.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}
</style>
